package com.hdu.h_health.news.widget;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hdu.h_health.news.Fragment1Adapter;
import com.hdu.h_health.R;
import com.hdu.h_health.bean.NewsBean;
import com.hdu.h_health.common.BaseFragment;
import com.hdu.h_health.news.view.BaseView;
import com.hdu.h_health.news.presenter.InfoPresenter;
import com.hdu.h_health.news.presenter.InfoPresenterItf;
import com.hdu.h_health.ui.NewsDetailsActivity;
import com.hdu.h_health.ui.WeeklyDetailsActivity;
import com.hdu.h_health.utils.CommonUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 精选资讯
 * Created by 612 on 2016/2/26.
 */
public class Fragment1 extends BaseFragment implements
        BaseView<NewsBean>, SwipeRefreshLayout.OnRefreshListener,
        Fragment1Adapter.OnItemClickListener {

    @Bind(R.id.rc_view)
    RecyclerView rcView;
    @Bind(R.id.sw_refresh)
    SwipeRefreshLayout swRefresh;

    private Fragment1Adapter adapter;
    private List<NewsBean> newsBeans = new ArrayList<>();

    private LinearLayoutManager mLayoutManager;
    private InfoPresenter infoPresenter;

    private boolean isPrepared;//标志已经初始化完成
    private int currentPage = 0;//当前页
    private int mType;//资讯类型

    //提供实例化接口给NewsFragment调用
    public static Fragment1 newInstance(int type) {
        Bundle args = new Bundle();
        Fragment1 fragment = new Fragment1();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        infoPresenter = new InfoPresenterItf(this);//上溯造型
        mType = getArguments().getInt("type");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1, container, false);
        ButterKnife.bind(this, view);
        initSwRefresh();
        initRecyclerView();
        //控件准备好了
        isPrepared = true;
        //延时加载数据
        lazyLoad();
        return view;
    }

    //初始化刷新布局
    private void initSwRefresh() {
        swRefresh.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary);
        swRefresh.setOnRefreshListener(this);
    }

    //初始化RecyclerView
    private void initRecyclerView() {
        mLayoutManager = new LinearLayoutManager(getActivity());
        rcView.setLayoutManager(mLayoutManager);
        rcView.setItemAnimator(new DefaultItemAnimator());//设置分隔线
        adapter = new Fragment1Adapter(getActivity(), newsBeans);
        adapter.setOnItemClickListener(this);
        rcView.setAdapter(adapter);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_weekmagazine, rcView, false);
        adapter.setHeaderView(view);
        rcView.addOnScrollListener(mOnScrollListener);
    }

    //RecyclerView滑动监听
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {

        private int lastVisibleItem;//最后一个Item的位置

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();//设置最后一个Item的位置
        }

        //滑动状态
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            adapter.isShowFooter(true);
            if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItem + 1 == adapter.getItemCount()
                    && adapter.isShowFooter()) {
                //调用Presenter层的loadNews方法加载更多
                infoPresenter.loadInfo(getActivity(), currentPage, mType);
            }
        }
    };

    @Override
    public void showProgress() {
        swRefresh.setRefreshing(true);
    }

    @Override
    public void addData(List<NewsBean> newsList) {
        if (newsList == null) return;
        if (newsBeans == null) newsBeans = new ArrayList<>();
        if (newsList.size()>0) adapter.isShowFooter(true);
        if (currentPage == 0 && newsBeans.size() > 0 && newsList.size() > 0) {
            newsBeans.clear();
        } else {
            //TODO　如果没有更多数据了,则隐藏footer布局（隐藏动画生硬）
            if (newsList.size() == 0) {
                CommonUtils.showLog("没有更多了");
                CommonUtils.showToast(getActivity(), "没有更多数据了");
                adapter.isShowFooter(false);
            }
        }
        newsBeans.addAll(newsList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void hideProgress() {
        swRefresh.setRefreshing(false);
    }

    @Override
    public void showLoadFailMsg(String error) {
        if (currentPage == 0) {
            adapter.isShowFooter(false);
            adapter.notifyDataSetChanged();
        }
        CommonUtils.showLog(error);
        CommonUtils.showToast(getActivity(), getResources().getString(R.string.NetworkError));
    }

    @Override
    public void changePage(int page) {
        this.currentPage = page;
    }

    @Override
    public void onItemClick(View view, int position) {
        if (position == 0) {
            startActivity(new Intent(getActivity(), WeeklyDetailsActivity.class));
        } else {
            NewsBean newsBean = newsBeans.get(position - 1);//因为有头部布局
            Intent intent = new Intent(getActivity(), NewsDetailsActivity.class);
            intent.putExtra(NewsDetailsActivity.URL, newsBean.getUrl());
            startActivity(intent);
        }
    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        //调用Presenter控制层的loadInfo加载数据
        infoPresenter.loadInfo(getActivity(), currentPage, mType);
    }

    //Fragment可见时才调用——网络加载
    @Override
    protected void lazyLoad() {
        //初始化完成并且可见
        if (!isPrepared || !isVisible) {
            return;
        }
        //判断是否是第一次加载数据
        if (newsBeans.size() == 0) {
            //从后台加载数据
            onRefresh();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
